<template>
  <div class="inventory-distribution-container">
    <!-- 产品信息展示区域 -->
    <div class="product-info-section">
      <div class="product-info-card">
        <div class="product-name">
          {{ productInfo.productName || '未获取到商品信息' }} 
          {{ productInfo.productNo ? `(${productInfo.productNo})` : '' }}
        </div>
        <div class="product-details">
          <span class="detail-item">
            <label>商品ID：</label>
            <span>{{ route.query.id || '未传递' }}</span>
          </span>
          <span class="detail-item">
            <label>货品类型：</label>
            <span>{{ productInfo.productType || '未获取' }}</span>
          </span>
          <span class="detail-item">
            <label>规格型号：</label>
            <span>{{ productInfo.productModel || '未获取' }}</span>
          </span>
          <span class="detail-item">
            <label>单位：</label>
            <span>{{ productInfo.unitName || '未获取' }}</span>
          </span>
        </div>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="statistics-section">
      <div class="statistics-cards">
        <div class="stat-card current-inventory-card">
          <div class="stat-title">当前库存</div>
          <div class="stat-value current-value">{{ statistics.currentInventory.toLocaleString() }}</div>
        </div>
        
        <div class="stat-card available-inventory-card">
          <div class="stat-title">可用库存</div>
          <div class="stat-value available-value">{{ statistics.availableInventory.toLocaleString() }}</div>
        </div>
        
        <div class="stat-card pending-outbound-card">
          <div class="stat-title">待出库</div>
          <div class="stat-value outbound-value">{{ statistics.pendingOutbound.toLocaleString() }}</div>
        </div>
        
        <div class="stat-card pending-inbound-card">
          <div class="stat-title">待入库</div>
          <div class="stat-value inbound-value">{{ statistics.pendingInbound.toLocaleString() }}</div>
        </div>
      </div>
    </div>

    <!-- 表格操作区域 -->
    <div class="table-actions">
      <el-button type="default" @click="handleExport">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="AddRow">新增</el-button>
      <el-button type="info" @click="handleRefreshProductInfo">刷新商品信息</el-button>
      <el-button type="success" @click="handleRefreshStatistics">刷新统计</el-button>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="180" />
        <el-table-column prop="inventory" label="仓库名称" width="180" />
        <el-table-column prop="location" label="仓位名称" width="180" />
        <el-table-column prop="current_Inventory" label="当前库存" width="180" />
        <el-table-column prop="available_Inventory" label="可用库存" width="200" />
        <el-table-column prop="waitIn" label="待入库" width="180" />
        <el-table-column prop="waitOut" label="待出库" width="180" />
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 库存分布新增 -->
    <el-dialog v-model="dialogVisible" title="新增库存分布" width="600px" :close-on-click-modal="false" @close="handleDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="inventory">
               <el-select v-model="addForm.inventory" placeholder="请输入仓库名称" style="width: 100%">
                 <el-option label="仓库一" value="仓库一" />
                 <el-option label="仓库二" value="仓库二" />
                 <el-option label="仓库三" value="仓库三" />
               </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位名称" prop="location">
              <el-select v-model="addForm.location" placeholder="请选择库位名称" style="width: 100%">
                 <el-option label="库位一" value="库位一" />
                 <el-option label="库位二" value="库位二" />
                 <el-option label="库位三" value="库位三" />
               </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="可用库存" prop="available_Inventory">
              <el-input-number 
                v-model="addForm.available_Inventory" 
                :min="0" 
                placeholder="请输入可用库存"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="待入库" prop="waitIn">
              <el-input-number 
                v-model="addForm.waitIn" 
                :min="0" 
                placeholder="请输入待入库数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="待出库" prop="waitOut">
              <el-input-number 
                v-model="addForm.waitOut" 
                :min="0" 
                placeholder="请输入待出库数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存上限" prop="upperlimit">
              <el-input-number 
                v-model="addForm.upperlimit" 
                :min="0" 
                placeholder="请输入库存上限"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存下限" prop="lowerlimit">
              <el-input-number 
                v-model="addForm.lowerlimit" 
                :min="0" 
                placeholder="请输入库存下限"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit" :loading="addLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { TZRead, TZWrite } from '@/http/interceptors'
import { useRoute } from 'vue-router'

const route = useRoute()

// 查询表单数据
const searchForm = reactive({
  productId: route.query.id // 从路由参数获取商品ID
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 商品详情数据
const productInfo = reactive({
  productName: '',
  productNo: '',
  productType: '',
  productModel: '',
  unitName: '',
  productId: null
})

// 统计数据
const statistics = reactive({
  currentInventory: 0,
  availableInventory: 0,
  pendingOutbound: 0,
  pendingInbound: 0
})

// 新增表单数据
const addForm = reactive({
  product_Id: parseInt(route.query.id), // 商品ID，从路由参数获取
  inventory: '',
  location: '',
  current_Inventory: 0,
  available_Inventory: 0,
  waitIn: 0,
  waitOut: 0,
  upperlimit: 0,
  lowerlimit: 0
})

// 新增表单验证规则
const addFormRules = reactive({
  inventory: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入库位名称', trigger: 'blur' }],
  current_Inventory: [{ required: true, message: '请输入当前库存', trigger: 'blur' }],
  available_Inventory: [{ required: true, message: '请输入可用库存', trigger: 'blur' }],
  waitIn: [{ required: true, message: '请输入待入库数量', trigger: 'blur' }],
  waitOut: [{ required: true, message: '请输入待出库数量', trigger: 'blur' }],
  upperlimit: [{ required: true, message: '请输入库存上限', trigger: 'blur' }],
  lowerlimit: [{ required: true, message: '请输入库存下限', trigger: 'blur' }]
})

// 新增表单 ref
const addFormRef = ref(null)
const addLoading = ref(false)

// 获取商品信息
const getProductInfo = async () => {
  try {
    const productId = route.query.id
    if (!productId) {
      ElMessage.error('缺少商品ID参数')
      return
    }

    console.log('获取商品信息，商品ID:', productId)
    
    const res = await TZRead.get("/api/Product/list", { 
      params: { 
        pageIndex: 1, 
        pageSize: 1,
        productId: productId 
      } 
    })
    
    console.log('商品信息API响应:', res.data)
    
    if (res.data.code === 200 && res.data.pageData && res.data.pageData.length > 0) {
      const product = res.data.pageData[0]
      
      // 更新商品信息
      productInfo.productId = product.id
      productInfo.productName = product.productName || ''
      productInfo.productNo = product.productNo || ''
      productInfo.productType = product.productTypeId || ''
      productInfo.productModel = product.productModel || ''
      productInfo.unitName = product.unitName || ''
      
      console.log('获取到商品信息:', productInfo)
      
      // 设置查询表单的商品ID
      searchForm.productId = productId
      
      // 设置新增表单的默认值
      addForm.product_Id = parseInt(productId)
      
    } else {
      console.warn('未找到商品信息，使用默认值')
      // 设置默认商品信息，避免页面显示异常
      productInfo.productName = '商品信息获取中...'
      productInfo.productNo = route.query.id || ''
      productInfo.productType = '未知'
      productInfo.productModel = '未知'
      productInfo.unitName = '未知'
      
      // 设置新增表单的默认值
      addForm.product_Id = parseInt(productId)
      
      ElMessage.warning('未找到商品信息，请检查商品ID是否正确')
    }
  } catch (error) {
    console.error('获取商品信息失败:', error)
    
    // 设置默认商品信息，避免页面显示异常
    productInfo.productName = '商品信息获取失败'
    productInfo.productNo = route.query.id || ''
    productInfo.productType = '未知'
    productInfo.productModel = '未知'
    productInfo.unitName = '未知'
    
    // 设置新增表单的默认值
    addForm.product_Id = parseInt(route.query.id) || 0
    
    ElMessage.error('获取商品信息失败，请检查网络连接')
  }
}

// 从仓库分布数据中提取商品信息（备用方案）
const extractProductInfo = (data) => {
  console.log('提取商品信息 - 原始数据:', data)
  
  if (data && data.length > 0) {
    // 从第一条记录中提取商品信息（因为都是同一个商品）
    const firstRecord = data[0]
    console.log('第一条记录:', firstRecord)
    
    // 从联表查询返回的数据中提取商品信息
    if (!productInfo.productName) {
      productInfo.productName = firstRecord.productName || ''
    }
    if (!productInfo.productNo) {
      productInfo.productNo = firstRecord.productNo || ''
    }
    if (!productInfo.productType) {
      productInfo.productType = firstRecord.productTypeId || ''
    }
    if (!productInfo.productModel) {
      productInfo.productModel = firstRecord.productModel || ''
    }
    if (!productInfo.unitName) {
      productInfo.unitName = firstRecord.unitName || ''
    }
    
    console.log('从仓库数据提取商品信息:', productInfo)
  } else {
    console.log('没有数据，无法提取商品信息')
  }
}

// 获取库存查询页面的统计数据
const getInventoryStatistics = async () => {
  try {
    const productId = route.query.id
    if (!productId) return

    console.log('获取库存统计数据，商品ID:', productId)
    
    // 调用库存查询接口获取统计数据
    const res = await TZRead.get("/api/Product/list", { 
      params: { 
        pageIndex: 1, 
        pageSize: 1,
        productId: productId 
      } 
    })
    
    if (res.data.code === 200 && res.data.pageData && res.data.pageData.length > 0) {
      const product = res.data.pageData[0]
      
      // 更新当前库存统计（从库存查询页面获取）
      statistics.currentInventory = product.current_Inventory || 0
      
      console.log('获取到库存统计数据:', {
        currentInventory: statistics.currentInventory,
        product: product
      })
    }
  } catch (error) {
    console.error('获取库存统计数据失败:', error)
  }
}

// 更新统计数据
const updateStatistics = (data) => {
  let availableTotal = 0
  let waitInTotal = 0
  let waitOutTotal = 0
  
  data.forEach(item => {
    availableTotal += item.available_Inventory || 0
    waitInTotal += item.waitIn || 0
    waitOutTotal += item.waitOut || 0
  })
  
  // 当前库存从库存查询页面获取，这里只更新其他统计
  statistics.availableInventory = availableTotal
  statistics.pendingInbound = waitInTotal
  statistics.pendingOutbound = waitOutTotal
  
  console.log('更新统计数据:', statistics)
}

// 查询数据
const loadData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    // 确保商品ID参数存在
    if (route.query.id) {
      params.Product_Id = parseInt(route.query.id)
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    console.log('查询参数:', params)
    const res = await TZRead.get("/api/Product/warehouse-list", { params })
    
    console.log('API响应:', res.data)
    
    if (res.data.code === 200) {
      // 处理数据：添加序号
      const processedData = res.data.pageData.map((item, index) => {
        return {
          ...item,
          index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1
        }
      })
      
      tableData.value = processedData
      pagination.total = res.data.totalCount
      
      // 从仓库数据中提取商品信息（接口已返回货品信息）
      extractProductInfo(res.data.pageData)
      
      // 更新统计数据
      updateStatistics(res.data.pageData)
      
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.data.message || '查询失败')
    }
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 刷新按钮
const handleRefresh = () => {
  loadData()
}

// 刷新商品信息按钮
const handleRefreshProductInfo = async () => {
  await getProductInfo()
  ElMessage.success('商品信息已刷新')
}

// 刷新统计数据按钮
const handleRefreshStatistics = async () => {
  await getInventoryStatistics()
  ElMessage.success('统计数据已刷新')
}

// 导出按钮
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.pageIndex = page
  loadData()
}

// 当前库存变化处理
const handleCurrentInventoryChange = (value) => {
  // 移除自动调整逻辑，允许用户自由输入
}

// 新增弹窗关闭时重置表单
const handleDialogClose = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 新增提交
const handleAddSubmit = async () => {
  if (!addFormRef.value) return

  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      addLoading.value = true
      try {
        const res = await TZWrite.post("/api/ProductAddwarehouse", addForm)

        if (res.data.code === 200) {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          loadData() // 刷新表格
        } else {
          ElMessage.error(res.data.message || '新增失败')
        }
      } catch (error) {
        ElMessage.error('新增失败：' + error.message)
      } finally {
        addLoading.value = false
      }
    } else {
      ElMessage.error('请检查输入信息')
    }
  })
}

// 页面加载时执行
onMounted(async () => {
  console.log('路由参数:', route.query)
  console.log('商品ID:', route.query.id)
  
  // 先获取商品信息
  await getProductInfo()
  
  // 获取库存统计数据
  await getInventoryStatistics()
  
  // 再加载仓库分布数据
  await loadData()
})

//新增
const dialogVisible = ref(false)
const AddRow = () => {
  // 重置表单
  addForm.product_Id = parseInt(route.query.id)
  addForm.inventory = ''
  addForm.location = ''
  addForm.current_Inventory = 0
  addForm.available_Inventory = 0
  addForm.waitIn = 0
  addForm.waitOut = 0
  addForm.upperlimit = 1000 // 默认库存上限
  addForm.lowerlimit = 10   // 默认库存下限
  
  // 打开弹窗
  dialogVisible.value = true
}


</script>

<style scoped>
.inventory-distribution-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.product-info-section {
  margin-bottom: 20px;
}

.product-info-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.product-details {
  display: flex;
  gap: 30px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #666;
  margin-right: 5px;
}

.statistics-section {
  margin-bottom: 20px;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
}

.current-value {
  color: #409eff;
}

.available-value {
  color: #409eff;
}

.outbound-value {
  color: #e6a23c;
}

.inbound-value {
  color: #e6a23c;
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-section {
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 新增弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 